package com.atguigu.gmall.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.java.tuple.Tuple2;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * Author: Felix
 * Date: 2021/11/9
 * Desc: 用户维度查询的工具类
 */
public class DimUtil {

    public static JSONObject getDimInfo(String tableName, String id) {
        return getDimInfo(tableName,Tuple2.of("ID",id));
    }
    //获取维度信息        优化：加入旁路缓存
    //选型：Redis   类型：String      TTL:1day   Key:   dim:维度表名:主键值1_主键值2
    public static JSONObject getDimInfo(String tableName, Tuple2<String, String>... colNameAndValues) {

        //拼接查询语句
        StringBuilder selectDimSql = new StringBuilder("select * from " + tableName + " where ");
        //拼接查询Redis的key
        StringBuilder redisKey = new StringBuilder("dim:" + tableName.toLowerCase() + ":");

        //拼接查询条件和RedisKey的主键
        for (int i = 0; i < colNameAndValues.length; i++) {
            Tuple2<String, String> colNameAndValue = colNameAndValues[i];
            String colName = colNameAndValue.f0;
            String colValue = colNameAndValue.f1;
            selectDimSql.append(colName + "='" + colValue + "'");
            redisKey.append(colValue);

            if (i < colNameAndValues.length - 1) {
                selectDimSql.append(" and ");
                redisKey.append("_");
            }
        }

        //-----从Redis中获取缓存的维度数据-----
        Jedis jedis = null;
        String jsonStr = null;
        JSONObject dimJsonObj = null;

        try {
            jedis = RedisUtil.getJedis();
            jsonStr = jedis.get(redisKey.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("从Redis中查询缓存的维度数据失败");
        }

        //判断是否从Redis缓存中查询出了维度数据
        if (jsonStr != null && jsonStr.length() > 0) {
            //如果从Redis中查到了数据（命中缓存）  直接将查询的数据转换为json对象  进行返回
            dimJsonObj = JSON.parseObject(jsonStr);
        }else {
            //如果从Redis中没有查到数据，发送请求到phoenix中查询数据，并将查询的数据缓存到Redis中
            System.out.println("查询维度的SQL:" + selectDimSql);
            //底层还是调用PhoenixUtil
            List<JSONObject> dimJsonObjList = PhoenixUtil.queryList(selectDimSql.toString(), JSONObject.class);
            if (dimJsonObjList != null && dimJsonObjList.size() > 0) {
                //因为根据主键查询维度，所以只会有一条数据
                dimJsonObj = dimJsonObjList.get(0);
                //缓存到Redis
                if(jedis != null){
                    jedis.setex(redisKey.toString(),24*3600,dimJsonObj.toJSONString());
                }
            } else {
                System.out.println("维度数据没有找到" + selectDimSql);
            }
        }

        //释放资源
        if(jedis != null){
            jedis.close();
            System.out.println("---关闭Jedis连接---");
        }

        return dimJsonObj;
    }

    public static JSONObject getDimInfoNoCache(String tableName, Tuple2<String, String>... colNameAndValues) {

        StringBuilder selectDimSql = new StringBuilder("select * from " + tableName + " where ");

        //拼接查询条件
        for (int i = 0; i < colNameAndValues.length; i++) {
            Tuple2<String, String> colNameAndValue = colNameAndValues[i];
            String colName = colNameAndValue.f0;
            String colValue = colNameAndValue.f1;
            selectDimSql.append(colName + "='" + colValue + "'");
            if (i < colNameAndValues.length - 1) {
                selectDimSql.append(" and ");
            }
        }
        System.out.println("查询维度的SQL:" + selectDimSql);
        //底层还是调用PhoenixUtil
        List<JSONObject> dimJsonObjList = PhoenixUtil.queryList(selectDimSql.toString(), JSONObject.class);
        JSONObject dimJsonObj = null;
        if (dimJsonObjList != null && dimJsonObjList.size() > 0) {
            //因为根据主键查询维度，所以只会有一条数据
            dimJsonObj = dimJsonObjList.get(0);
        } else {
            System.out.println("维度数据没有找到" + selectDimSql);
        }

        return dimJsonObj;
    }

    //根据key 从Redis中删除掉缓存的维度数据
    public static void deleteCached(String tableName,String id){
        String key = "dim:" + tableName.toLowerCase() + ":" + id;
        try {
            Jedis jedis = RedisUtil.getJedis();
            jedis.del(key);
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //JSONObject dimInfo = DimUtil.getDimInfo("DIM_BASE_TRADEMARK", Tuple2.of("id", "17"));
        JSONObject dimInfo = DimUtil.getDimInfo("DIM_BASE_TRADEMARK", "18");
        System.out.println(dimInfo);
    }
}
